package com.mengniu.commerce.collect.controller;


import com.mengniu.commerce.admin.api.RemoteStoreService;
import com.mengniu.commerce.admin.api.domain.SysStore;
import com.mengniu.commerce.collect.service.IPushStrategy;
import com.mengniu.commerce.collect.third.response.item.ItemMessageResponse;
import com.mengniu.commerce.collect.util.WeiMengResultUtil;
import com.mengniu.commerce.common.core.constant.Constants;
import com.mengniu.commerce.common.core.domain.R;
import com.mengniu.commerce.common.core.exception.ServiceException;
import com.mengniu.commerce.common.core.utils.Md5Utils;
import com.mengniu.commerce.common.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;


/**
 * @Description: 微盟接收推送消息
 * @Param:
 * @return:
 * @Author: zfw
 * @Date: 2023/11/23
 * @Date: 19:23
 */
@RestController
@RequestMapping("/msg")
@Slf4j
public class WmReceiveMsgController {

    @Resource
    private RemoteStoreService remoteStoreService;

    @PostMapping("/receive")
    @ResponseBody
    public Object receive(@RequestBody ItemMessageResponse entity) {

        //获取参数
        try {
            Long bosId = entity.getBosId();
            R<SysStore> storeInfo = remoteStoreService.getStoreInfo(String.valueOf(bosId),"微盟");
            //空指针判断 todo
            storeInfo = Optional.ofNullable(storeInfo).orElse(R.fail());
            if(Constants.SUCCESS != storeInfo.getCode()){
                throw new ServiceException("店铺未配置不做处理");
            }
            String clientId="";
            String clientSecret="";
            if (Constants.SUCCESS == storeInfo.getCode()){
                clientId = storeInfo.getData().getClientId();
                clientSecret = storeInfo.getData().getClientSecret();
            }
            // 微盟md5加密方式  md5(clientId+id+msgBody+clientSecret)
            String sign = Md5Utils.MD5(clientId + entity.getId() + entity.getMsgBody().toString() + clientSecret);
            if (!sign.equals(entity.getSign())) {
                throw new ServiceException("消息不合法!");
            }
            // 消息的类型 调用不同实现 由微盟的topic+"_"+event来确定走什么消息
            String beanName = entity.getTopic()+"_"+entity.getEvent();
            if (!SpringUtils.containsBean(beanName)) {
                throw new ServiceException("消息类型为实现，eventType:" + entity.getEvent());
            }
            return IPushStrategy.push(entity.getBosId(),beanName, entity.getMsgBody().toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    return WeiMengResultUtil.restResult(0,"success");
    }

}


